﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PTUDW_CNTN2010_F_CDT.Models
{
    public class ShoppingCart
    {
        EcommerceDBContext db = new EcommerceDBContext();

        string ShoppingCartId { get; set; }

        public const string CartSession = "CartSessionId";

        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);

            return cart;
        }

        public void AddProductToCart(Product product)
        {
            var cart = db.Carts.SingleOrDefault(c => c.CartId == ShoppingCartId && c.ProductId == product.ProductId);

            if (cart == null)
            {
                cart = new Cart
                {
                    ProductId = product.ProductId,
                    CartId = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };
                db.Carts.Add(cart);
            }
            else
            {
                cart.Count++;
            }

            db.SaveChanges();
        }

        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSession] == null)
            {
                Guid random = Guid.NewGuid();
                context.Session[CartSession] = random.ToString();
            }

            return context.Session[CartSession].ToString();
        }

        public int GetCount()
        {
            int? count = (from cartItems in db.Carts
                          where cartItems.CartId == ShoppingCartId
                          select (int?)cartItems.Count).Sum();
            return count ?? 0;
        }

        public List<Cart> GetCartItems()
        {
            return db.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
        }

        public int CreateOrder(Order order)
        {
            float total = 0;

            var cartItems = GetCartItems();

            foreach (var item in cartItems)
            {
                var orderDetail = new OrderDetail
                {
                    ProductId = item.ProductId,
                    OrderId = order.OrderId,
                    UnitPrice = item.Product.Price,
                    Quantity = item.Count,
                };

                total += orderDetail.UnitPrice * orderDetail.Quantity;
                db.OrderDetails.Add(orderDetail);
            }

            order.Total = total;

            db.SaveChanges();

            return order.OrderId;
        }
    }
}